<template>
  <el-main>
    <div v-for="msg in msgs">

      <el-row v-if="msg.type === 'user'" justify="end" type="flex" style="margin-top: 10px;">
        <el-col :span="8">
          <el-tag effect="dark" type="plain" style="float: right;">
            Me
          </el-tag>
          <el-card shadow="hover" style="clear:both; color: whitesmoke;background-color: yellowgreen;">
            {{ msg.content }}
          </el-card>
        </el-col>
      </el-row>

      <el-row v-else>
        <el-row style="margin-top: 10px;">
          <el-col :span="8">
            <el-tag effect="dark" type="plain">
              客服
            </el-tag>
            <el-card shadow="hover" style=" color:black;background-color: lightblue;">
              {{ msg.content }}
            </el-card>
          </el-col>
        </el-row>
      </el-row>
    </div>

    <div style="position: absolute;bottom:0;left: 45%;">
      <el-form>
        <el-row>
          <el-col :span="18">
            <el-form-item>
              <el-input placeholder="请输入消息内容" v-model="msgInput"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-row>
              <el-button @click="sendMsg" size="medium">发送</el-button>
            </el-row>
          </el-col>
        </el-row>
      </el-form>
    </div>

  </el-main>
</template>

<script>
import { getUserProfile } from "@/api/system/user";
import { sendOneWebSocket, sendAllWebSocket } from "@/api/chatroom/message";
export default {
  data() {
    return {
      msgInput: "",
      user: {},
      roleGroup: {},
      postGroup: {},
      activeTab: "userinfo",
      msgs: [
        { "type": "system", "content": "期待您的积极咨询与反馈！！！" }
      ]
    };
  },
  destroyed() {
    // 离开页面时关闭websocket连接
    this.ws.onclose(undefined);
  },
  created() {
    this.getUser();
  },
  mounted() {

  },
  beforeDestroy() {
    this.onbeforeunload()
  },
  methods: {
    sendMsg() {
      sendOneWebSocket(this.msgInput, this.user.userId).then(response => {
        this.msgs.push(JSON.parse(response.data));
      })
    },
    getUser() {
      getUserProfile().then(response => {
        this.user = response.data;
        this.roleGroup = response.roleGroup;
        this.postGroup = response.postGroup;
        // WebSocket
        if ('WebSocket' in window) {
          // 这里没有api-dev才能运行
          console.log(process.env.VUE_APP_WEBSOCKET_URL + '/' + this.user.userId)
          this.websocket = new WebSocket(process.env.VUE_APP_WEBSOCKET_URL + '/' + this.user.userId)
          this.initWebSocket()

        } else {
          alert('当前浏览器 Not support websocket')
        }
      });

    },
    initWebSocket() {
      // 连接错误
      this.websocket.onerror = this.setErrorMessage

      // 连接成功
      this.websocket.onopen = this.setOnopenMessage

      // 收到消息的回调
      this.websocket.onmessage = this.setOnmessageMessage

      // 连接关闭的回调
      this.websocket.onclose = this.setOncloseMessage

      // 监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
      window.onbeforeunload = this.onbeforeunload
    },
    setErrorMessage() {
      this.$modal.msgError("反馈室连接失败");
      console.log('WebSocket连接发生错误   状态码：' + this.websocket.readyState)
    },
    setOnopenMessage() {
      this.$modal.msgSuccess("反馈室连接成功");
      console.log('WebSocket连接成功    状态码：' + this.websocket.readyState)

    },
    setOnmessageMessage(event) {
      // 根据服务器推送的消息做自己的业务处理
      console.log('服务端返回：' + event.data)
      let msg = JSON.parse(event.data)
      this.msgs.push(msg)

    },
    setOncloseMessage() {
      console.log('WebSocket连接关闭    状态码：' + this.websocket.readyState)
    },
    onbeforeunload() {
      this.closeWebSocket()
    },
    closeWebSocket() {
      this.websocket.close()
    }
  }
};
</script>

<style lang="scss" scoped>
.chat-box {
  margin: 0 auto;
  background: #fafafa;
  position: absolute;
  height: 100%;
  width: 100%;
  max-width: 700px;

  header {
    position: fixed;
    width: 100%;
    height: 3rem;
    background: #409eff;
    max-width: 700px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-weight: bold;
    color: white;
    font-size: 1rem;
  }

  .msg-box {
    position: absolute;
    height: calc(100% - 6.5rem);
    width: 100%;
    margin-top: 3rem;
    overflow-y: scroll;

    .msg {
      width: 95%;
      min-height: 2.5rem;
      margin: 1rem 0.5rem;
      position: relative;
      display: flex;
      justify-content: flex-start !important;

      .user-head {
        min-width: 2.5rem;
        width: 20%;
        width: 2.5rem;
        height: 2.5rem;
        border-radius: 50%;
        background: #f1f1f1;
        display: flex;
        justify-content: center;
        align-items: center;

        .head {
          width: 1.2rem;
          height: 1.2rem;
        }

        // position: absolute;
      }

      .user-msg {
        width: 80%;
        // position: absolute;
        word-break: break-all;
        position: relative;
        z-index: 5;

        span {
          display: inline-block;
          padding: 0.5rem 0.7rem;
          border-radius: 0.5rem;
          margin-top: 0.2rem;
          font-size: 0.88rem;
        }

        .left {
          background: white;
          animation: toLeft 0.5s ease both 1;
        }

        .right {
          background: #53a8ff;
          color: white;
          animation: toright 0.5s ease both 1;
        }

        @keyframes toLeft {
          0% {
            opacity: 0;
            transform: translateX(-10px);
          }

          100% {
            opacity: 1;
            transform: translateX(0px);
          }
        }

        @keyframes toright {
          0% {
            opacity: 0;
            transform: translateX(10px);
          }

          100% {
            opacity: 1;
            transform: translateX(0px);
          }
        }
      }
    }
  }

  .input-box {
    padding: 0 0.5rem;
    position: absolute;
    bottom: 0;
    width: 100%;
    height: 3.5rem;
    background: #fafafa;
    box-shadow: 0 0 5px #ccc;
    display: flex;
    justify-content: space-between;
    align-items: center;

    input {
      height: 2.3rem;
      display: inline-block;
      width: 100%;
      padding: 0.5rem;
      border: none;
      border-radius: 0.2rem;
      font-size: 0.88rem;
    }

    .btn {
      height: 2.3rem;
      min-width: 4rem;
      background: #e0e0e0;
      padding: 0.5rem;
      font-size: 0.88rem;
      color: white;
      text-align: center;
      border-radius: 0.2rem;
      margin-left: 0.5rem;
      transition: 0.5s;
    }

    .btn-active {
      background: #409eff;
    }
  }
}
</style>